<template>
  <a-form
    :model="queryParams"
    layout="inline"
    autocomplete="off"
    @finish="onFinish"
    class="s-search"
  >
    <a-row class="s-search-row">
      <a-col class="s-search-col">
        <a-form-item :label="t('sysRole2')" name="name">
          <a-input
            allowClear
            v-model:value="queryParams.name"
            :placeholder="t('placeholder149')"
            v-input.trim.textFilter
          >
          </a-input>
        </a-form-item>
        <a-form-item>
          <a-space :size="16">
            <a-button type="primary" html-type="submit">
              <template #default>{{ t("base.query") }}</template>
              <template #icon><search-outlined /></template>
            </a-button>
            <a-button type="default" @click="handleReset">
              {{ t("base.reset") }}
              <template #icon><delete-outlined /></template>
            </a-button>
          </a-space>
        </a-form-item>
      </a-col>

      <a-col>
        <a-button
          v-has="'roleApi.create'"
          type="primary"
          @click="handleAction('add')"
          :loading="addLoading"
          >{{ t("base.add") }}
          <template #icon>
            <i
              :class="`s-icon iconfont ${getSelfNodeIcon('roleApi.create')}`"
            />
          </template>
        </a-button>
      </a-col>
    </a-row>
  </a-form>

  <a-table
    :loading="tableLoading"
    class="s-table"
    :pagination="tablePage"
    :columns="columns"
    :data-source="tableData"
    @change="handleTableChange"
  >
    <template v-slot:bodyCell="{ value, text, index, column, record }">
      <template v-if="column.key === 'index'">
        <i>{{ index + 1 + (tablePage.current - 1) * tablePage.pageSize }}</i>
      </template>

      <template v-if="column.key === 'desc'">
        <im-tooltip :value="record.desc" />
      </template>

      <template v-if="column.key === 'permission_list'">
        <div class="s_flex_cell" v-if="value?.length">
          <i class="Dashed fs10">{{ value[0].name }}</i>
          <a-tooltip placement="top" color="#ffffff" trigger="hover">
            <!-- <template #title>
              <div class="s_title_containter">
                <div
                  class="title_wrap"
                  v-for="(item, index) in value.slice(1)"
                  :key="index"
                >
                  <i>{{ item.name }}</i>
                </div>
              </div>
            </template> -->
            <template v-slot:default>
              <i class="Dashed fs10" v-if="value.length - 1 > 0">
                {{ value.length - 1 }}</i
              >
            </template>
          </a-tooltip>
        </div>
      </template>

      <template v-if="column.key === 'action'">
        <div class="s-table-body_cell">
          <div v-has="'roleApi.update'">
            <a-button type="link" @click="handleAction('edit', record)"
              >{{ t("base.edit") }}
              <template #icon>
                <i
                  :class="`s-icon iconfont ${getSelfNodeIcon(
                    'roleApi.update'
                  )}`"
                />
              </template>
            </a-button>
            <a-divider type="vertical" />
          </div>
          <a-button
            type="link"
            v-has="'roleApi.queryDataById'"
            @click="handleAction('view', record)"
            >{{ t("base.detail") }}
            <template #icon>
              <i
                :class="`s-icon iconfont ${getSelfNodeIcon(
                  'roleApi.queryDataById'
                )}`"
              />
            </template>
          </a-button>
        </div>
      </template>
    </template>
  </a-table>
  <IMFormInline
    ref="drawerRef"
    @refreshTable="refreshTable"
    @fetchList="fetchList"
  />
</template>
<script lang="ts">
import { addLoading, tableLoading, operateType } from "./store";
import IMFormInline from "./components/drawer/index.vue";
import { IMTableType } from "@/types/table";
import { getSelfNodeIcon } from "@system/menu/store";
import { QueryParamsType } from "./type";
const columns = reactive<IMTableType[]>(
  defineColumns([
    {
      title: getProxyT("base.index"),
      dataIndex: "index",
      key: "index",
      align: "center",
    },
    {
      title: getProxyT("table203"),
      dataIndex: "name",
      key: "name",
      align: "center",
    },
    {
      title: getProxyT("table193"),
      dataIndex: "desc",
      key: "desc",
      align: "center",
    },
    {
      title: getProxyT("table204"),
      dataIndex: "userCount",
      key: "userCount",
      align: "center",
    },
    {
      title: getProxyT("table205"),
      dataIndex: "slug",
      key: "slug",
      align: "center",
    },
    {
      title: getProxyT("table206"),
      dataIndex: "permission_list",
      key: "permission_list",
      align: "center",
    },
    {
      title: getProxyT("table43"),
      dataIndex: "create_time",
      key: "create_time",
      align: "center",
      customRender: ({ text }: any) => getTimeByZone(text),
    },
    {
      title: getProxyT("table202"),
      dataIndex: "update_time",
      key: "update_time",
      align: "center",
      customRender: ({ text }: any) => getTimeByZone(text),
    },
    { title: getProxyT("base.action"), key: "action", align: "center" },
  ])
);

export default defineComponent({
  components: {
    IMFormInline,
  },
  setup() {
    const _this = reactive<any>(getCurrentInstance());
    const tableData = ref<any>([]);
    const tablePage = reactive<any>({
      total: 0,
      current: 1,
      pageSize: 10,
    });
    const queryParams = reactive<QueryParamsType>({
      name: undefined,
    });
    const fetchList = async () => {
      try {
        tableLoading.value = true;
        tableData.value = [];
        const res: any = await roleApi.query({
          page: tablePage.current,
          page_size: tablePage.pageSize,
          ...queryParams,
        });
        if (res.code != 200) return message.error(res.message);
        tableData.value = res?.data?.list ?? [];
        tablePage.total = res?.data?.attributes?.total ?? 0;
      } catch (error: any) {
        message.error(error.message);
      } finally {
        tableLoading.value = false;
      }
    };

    const refreshTable = async () => {
      tablePage.current = 1;
      await fetchList();
    };
    const handleReset = () => {
      clearObjAttr(queryParams);
      refreshTable();
    };
    const onFinish: any = (values: any) => {
      onFinish.timer && clearTimeout(onFinish.timer);
      onFinish.timer = setTimeout(() => refreshTable(), 200);
    };

    const handleTableChange = (paging: any) => {
      tablePage.current = paging.current;
      tablePage.pageSize = paging.pageSize;
      fetchList();
    };

    const handleAction = async (type: any, record?: any) => {
      operateType.value = type;
      switch (type) {
        case "add":
          _this.refs.drawerRef.showDrawer(type);
          break;
        case "edit":
          _this.refs.drawerRef.showDrawer(type, record);
          break;
        case "view":
          _this.refs.drawerRef.showDrawer(type, record);
          break;
      }
    };
    watch(
      () => sysZone.value,
      () => fetchList()
    );
    onActivated(() => fetchList());
    return {
      getSelfNodeIcon,
      t: $t,
      fetchList,
      handleReset,
      refreshTable,
      handleTableChange,
      handleAction,
      tablePage,
      tableData,
      columns,
      queryParams,
      onFinish,
      tableLoading,
      addLoading,
    };
  },
});
</script>
<style scoped lang="less">
.s-table {
  background-color: #fff;
}
</style>
@/types/table
